//
//  UIViewController+Help.m
//  MVVM+RAC
//
//  Created by bopeng on 16/6/14.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "UIViewController+Help.h"
#import <objc/runtime.h>

@implementation UIViewController (Help)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        methodSwizzling(class, @selector(viewWillAppear:), @selector(scott_viewWillAppear:));
        methodSwizzling(class, @selector(viewWillDisappear:), @selector(scott_viewWillDisappear:));
    });
}


void methodSwizzling(Class class, SEL originSelector, SEL swizzSelector){
    
    Method originMethod = class_getInstanceMethod(class, originSelector);
    Method swizzMethod = class_getInstanceMethod(class, swizzSelector);
    
    BOOL isAddMethod = class_addMethod(class, originSelector, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
    if (isAddMethod) {
        class_replaceMethod(class, swizzSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
    }else{
        method_exchangeImplementations(originMethod, swizzMethod);
    }
}


- (void)scott_viewWillAppear:(BOOL)animated {
    [self scott_viewWillAppear:animated];
//    NSLog(@"调用自定义viewWillAppear");
}

- (void)scott_viewWillDisappear:(BOOL)animated {
    [self scott_viewWillDisappear:animated];
//    NSLog(@"调用自定义viewWillDissappear");
}

@end
